/*
 *  Copyright 2014-2015 snakerflow.com
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *     http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */
package com.earl.mbasystem.security.shiro;

import java.text.MessageFormat;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.springframework.stereotype.Component;

import com.earl.mbasystem.domain.privilege.PrivilegeDao;
import com.earl.mbasystem.domain.privilege.PrivilegePo;

/**
 * 支持Shiro的插件
 * @author yuqs
 * @since 0.1
 */
@Component(value="shiroPlugin")
public class ShiroPlugin {
	
	private static Logger log = LogManager   
            .getLogger(ShiroPlugin.class);
	public static final String PREMISSION_FORMAT = "perms[\"{0}\"]";
	private static FilterChainManager manager = null;
	
	//需要Spring注入这个属性
	@Resource
	PrivilegeDao privilegeDao;
	
	//spring注入后，对自己引用，这样子才能保留注入，否则，自己new会出错
	@Resource(name = "shiroPlugin")
	ShiroPlugin mm;
	
	public ShiroPlugin(){
		System.out.println("");
	}

	public static ShiroPlugin getInstance() {
		return shiroPlugin;
	}
	
	static ShiroPlugin shiroPlugin;
	
	@PostConstruct
	public void init(){
		shiroPlugin = mm;
	}
	
	
	//配置shiro环境
	public void start(){
		if(manager == null) return ;
		
		List<PrivilegePo> resources = privilegeDao.findAll();

		for(PrivilegePo resource : resources) {
			String source = resource.getUrl();
			String authority = resource.getPrivilegeName();
			if(StringUtils.isEmpty(source)) {
				continue;
			}
			if(source.indexOf(";") != -1) {
				String[] sources = source.split(";");
				for(String singleSource : sources) {
					createChain(manager, singleSource, authority);
				}
			} else {
				createChain(manager, source, authority);
			}
		}
		manager.createChain("/**", "user");
	}
	
	private static void createChain(FilterChainManager manager, String key, String value) {
	    log.info("add authority url[url=" + key + "\tvalue=" + value + "]");
	    manager.createChain(key, MessageFormat.format(PREMISSION_FORMAT, value));
	}

	public static void setFilterChainManager(FilterChainManager manager) {
		ShiroPlugin.manager = manager;
	}

}
